# -*- coding:utf-8 -*-
import pymongo
import urllib
import os, sys
import traceback
import time
from pymongo import MongoClient
from pymongo.errors import BulkWriteError
sys.path.append(os.path.join(os.path.abspath(os.path.dirname(__file__)), os.pardir, os.pardir))
import supeanut_config
from CommonLib.mylog import mylog


class MongoDBTool:
	# pymongo version 3.4.0
	def __init__(self, conn_str=None):
		if conn_str is None:
			conn_str = supeanut_config.MONGO_CONN_STR
		#self.conn_str = urllib.quote(conn_str)
		self.conn_str = conn_str

	def conn(self, db, coll):
		try:
			self.client = MongoClient(self.conn_str)
			self.db = self.client[db]
			self.coll = self.db[coll]
		except:
			return False, 'failed to connect mongodb:%s'%traceback.format_exc()
		conn_suc = False
		while not conn_suc:
			try:
				self.client.database_names()
			except:
				# timeout:重要的判断字段，默认mongo失连，可能为触发cgroup内存限制
				time.sleep(1)
				# 写日志...
				continue
			conn_suc = True
		return True, 'suc to conn mongodb'

	def client_sample(self):
		print "### Show DataBase ###"
		print self.client.database_names()
		print "### Delete DB ###" 
		#self.client.drop_database('Supeanut')
		print "### Max connections to Server ###" 
		print self.client.max_pool_size
		print "### Set of all currently connected servers ###" 
		print self.client.nodes
		print "### The largest BSON object the connected server accepts in bytes ###" 
		print self.client.max_bson_size
		print "### The largest message the connected server accepts in bytes ###" 
		print self.client.max_message_size
		print "### Server Info ###" 
		print self.client.server_info()
		print "### close ###" 
		print self.client.close()

	def db_sample(self):
		print "### Show Collections ###"
		print self.db.collection_names()
		print "### Delete Collection ###"
		print self.db.drop_collection('DayDate')

	def coll_sample(self):
		# index 
		self.coll.create_index([('mike',pymongo.ASCENDING),\
							   ('eliot',pymongo.ASCENDING)],\
							   unique = True,\
							   name = 'mike_eliot')
		self.coll.drop_index('mike_eliot')
		self.coll.reindex()
		self.coll.index_information()
		# insert
		self.coll.insert_one({'mike':1,'eliot':2,'info':'123'})
		self.coll.insert_many()
		# replace
		self.coll.replace_one({'mike':5},{'mike':6,'info':222},upsert=False)
		# update
		self.coll.update_one({'mike':6},{'$inc':{'mike':6}},upsert=False)
		self.coll.update_many({'mike':6},{'$inc':{'mike':6}},upsert=False)
		# delete
		self.coll.delete_one({'mike':6})
		self.coll.delete_many({'mike':6})
		# search
		docs_iter = self.coll.find(filter={'mike':6}, \
								   projection=['mike', 'info'])
		docs_iter = docs_iter.sort([('mike',pymongo.ASCENDING)])
		# just check exsits, return None or doc
		doc = self.coll.find_one({'mike':6})
		# summary
		self.coll.count({'mike':6})
		self.coll.distinct(key='mike',\
						   filter={"eliot": {'$exists': True }})
		# rename
		self.coll.rename('test_2')
		# count
		#docs.count()

if __name__ == '__main__':
	conn_str = None
	mongodb_obj = MongoDBTool(conn_str)



	#print mongodb_obj.conn('Supeanut', 'ExRights')
	#print mongodb_obj.conn('Supeanut', "TradeCalendar")
	#docs = mongodb_obj.coll.find({})
	#docs = mongodb_obj.coll.find({'date':{'$gte':'2017-02-28'}})
	print mongodb_obj.conn('Supeanut', 'DayData')
	docs = mongodb_obj.coll.find({'code':'sz000505'})
	count = 0
	for doc in docs:
		print doc
		count += 1
	print count
	exit(0)


	print mongodb_obj.conn('Supeanut', 'Predict')
	docss = mongodb_obj.coll.find({'date':'2017-06-21'})
	for docs in docss:
		for doc in docs['predict']:
			print doc
	'''
	print mongodb_obj.conn('Supeanut', 'Predict')
	mongodb_obj.coll.update_one({'date':'2017-06-09'},{'$set':{'date':'2017-06-09', \
	'predict':[\
	[0.0359475, u'002453','',[],[]],\
	[0.0359475, u'002193','',[],[]],\
	[0.035331999999999995, u'002335', '',[],[]],\
	[0.0326427387, u'002740', '',[],[]],\
	[0.02763905665948642, u'000619', '',[],[]],\
	[0.026949318599999997, u'300561', '',[],[]],\
	[0.026949318599999997, u'000068', '',[],[]],\
	[0.026750447599999998, u'603908', '',[],[]],\
	[0.0241473928, u'002668', '',[],[]],\
	[0.0241473928, u'600121', '',[],[]],\
	]}},upsert=False)
	'''
